package com.ys.controller.api.purchase;


import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgPurchaseOrderPay;
import com.ys.entity.sys.YsCol;
import com.ys.enume.purchase.TcgPurchaseByOrderEnum;
import com.ys.service.purchase.Api1688Service;
import com.ys.service.purchase.TcgPurchaseOrderPayService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 采购付款
 */
@Controller
@RequestMapping("/api/inter/tcgPurchaseOrderPay")
public class ApiInterTcgPurchaseOrderPayController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgPurchaseOrderPayController.class);

    @Autowired
    private CommonApiService<TcgPurchaseOrderPay> commonApiService;


    @Autowired
    private Api1688Service api1688Service;

    @Autowired
    private TcgPurchaseOrderPayService tcgPurchaseOrderPayService;

    @Autowired
    private CheckUtil checkUtil;

    //菜单id
    private Long menuId = MenuId.TCG_PurchaseOrderPay;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgPurchaseOrderPay:view";
    private final String PERMISSIONS = "tcgPurchaseOrderPay:";


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgPurchaseOrderPay setSeachSql(TcgPurchaseOrderPay cond){

        cond

                .addLeftJoin("TCG_PurchaseByOrder AA ON A.PurchaseOrderBid = AA.Bid")
                .addField("FORMAT(AA.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByOrder")//创建时间
                .addField("FORMAT(AA.AuditingTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTimeByOrder")//订单审核时间
                .addField("AA.OrderStatus AS _ys_orderStatus")//采购管理状态
                .addField("AA.SpBm AS spBm")//商品编码
                .addField("AA.AliAccount AS aliAccount")//1688账号
                .addField("AA.AliOrderNumber AS aliOrderNumber")//1688订单编号
                .addField("AA.AliMessage AS aliMessage")//1688留言
                .addField("AA.AliState AS aliState")//1688订单状态
                .addField("AA.OrderAmount AS orderAmount")//实际订单金额（含运）
                .addField("AA.PurchaseOrderAmount AS purchaseOrderAmount")//采购订单金额（含税）
                .addField("AA.FreightCharge AS freightCharge")//实际运费
                .addField("AA.ServiceCharge AS serviceCharge")//采购服务费
                .addField("AA.Vgsbm AS vgsbm")//运营公司编码
                .addField("AA.OrderAmountExpect AS orderAmountExpect")//预计采购订单金额

                .addField("CASE WHEN AA.PlanToOrderNo IS NOT NULL  THEN CAST(AA.PlanToOrderNo AS varchar(50)) + '/' +  CAST(AA.PlanToOrderNum AS varchar(50)) + ' ' + AA.CreateMonth + '-NO.' + CAST(AA.MonthNo AS varchar(50)) ELSE '' END  assembleSign ")//组装标识


                .addLeftJoin("TS_UserChange B ON B.UserId = AA.AuditingUserId AND B.Status = 1")
                .addField("B.UserId + '/' + B.UserName AS _ys_auditingUserName")//订单审核人

                .addLeftJoin("TCG_PurchaseByOrderSon C ON C.Pid = AA.Id ")//采购订单 (子表
                .addField("C.Sku AS sku")//SKU属性
                .addField("C.RealitySku AS realitySku")//实际SKU属性
                .addField("C.SkuId AS skuId")//skuId
                .addField("C.SpecId AS specId")//specId
                .addField("C.RealityPrice AS realityPrice")//子件实际单价
                .addField("C.SubRealityPrice AS subRealityPrice")//子件单价（采购销售）
                .addField("C.RealityCost AS realityCost")//子件总价（采购销售）
                .addField("C.SubCostPrice AS subCostPrice")//子件单价（采购成本）
                .addField("C.CostPriceTotal AS costPriceTotal")//子件总价（采购成本）
                .addField("C.SubCode AS subCode")//子商品编码
                .addField("C.SupplierId AS supplierId")//供应商ID
                .addField("C.SupplierName AS supplierName")//供应商名称

                .addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = AA.Vgsbm ")//运营公司管理表
                .addField("E.Vgsjc AS vgsjc")//采购公司简称
                .addField("E.Vgsmc AS vgsmc")//采购公司名称

                .addLeftJoin("TCG_PurchaseAddress F ON F.Id = AA.PurchaseAddressId ")//采购地址维护
                .addField("F.VGjH + ',' + F.VSfH + ',' + F.VDsH + ',' + F.VCqH + ',' + F.VDzH  AS addressDetail")//采购地址

                .addLeftJoin("TP_ProductBasis G ON G.Code = AA.SpBm ")//商品母件信息表
                .addField("G.Name AS spName")//商品名称

                .addLeftJoin("TCG_PurchaseByPlan H ON H.Bid = AA.PlanBid")//采购计划表
                .addField("H.EffectStock AS effectStockByPlan")//计划审核状态
                .addField("H.Remark AS remarkByPlan")//整单备注
                .addField("FORMAT(H.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByPlan")//计划创建时间

                .addLeftJoin("TCG_PurchasePlanGoods I ON I.Id = AA.PurchasePlanGoodsId")//采购计划母件表
                .addField("I.StockAmount AS stockAmount")//库存数量
                .addField("I.SpAmount AS spAmount")//采购数量

                .addLeftJoin("TCG_PurchaseByPlanSon J ON J.Id = C.PurchasePlanSonId ")//计划单子件信息表
                .addField("J.SubName AS subName")//子件商品名称
                .addField("J.SubAmount AS subAmount")//子件BOM数量
                .addField("J.Bprice AS bprice")//子件BOM单价、预估单价
                .addField("J.SubRemark AS subRemark")//子件BOM备注
                .addField("J.SubStockAmount AS subStockAmount")//子件库存数量
                .addField("J.PurchaseAmount AS purchaseAmount")//子件采购数量=母件采购数量*子件数量
                .addField("J.JgSl AS jgSl")//子件加购数量
                .addField("J.SubTotalAmount AS subTotalAmount")//子件采购总数
                .addField("J.SubTotalPrice AS subTotalPrice")//子件预估总价

                .addLeftJoin("TS_UserChange K ON K.Id = H.CreateChangeId ")
                .addField("K.UserId + '/' + K.UserName AS _ys_createUserNameByPlan")//计划制单人
                .addField("K.DeptName AS deptNameByPlan")//部门
                .addField("K.RoleName AS roleNameByPlan")//岗位

                .addLeftJoin("YS_ProcInst L ON L.Bid = H.Bid ")
                .addField("FORMAT(L.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTimeByPlan")//审核时间


                .addLeftJoin("TS_UserChange M ON M.UserId = A.AuditingUserId AND M.Status = 1")
                .addField("M.UserId + '/' + M.UserName AS _ys_auditingUserNameByPay")//审核人


        .setOrderby("A.Bid DESC");//排序


        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgPurchaseOrderPay cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_auditingUserName");//订单审核人
            if (nameLinked != null){
                cond.where("B.UserId LIKE '%" + nameLinked + "%'" + " OR  B.UserName LIKE '%" + nameLinked + "%'");
            }

            String orderStatus = ConditionUtil.getConditionValue(conditions, "_ys_orderStatus");//订单状态
            if (orderStatus == null || "".equals(orderStatus)){
                //获取查询页面默认显示的状态
                List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getPaySearchStatus();
                //拼接
                String orders = TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList);
                cond.where("AA.OrderStatus IN ("+ orders +")");
            }else {
                //-1时显示全部状态
                //非-1时显示选择的对应状态
                if(!"-1".equals(orderStatus)){
                    cond.where("AA.OrderStatus  = "+orderStatus);
                }
            }

            cond = commonApiService.dataAuth(menuId, cond);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }




    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgPurchaseOrderPay cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = commonApiService.dataAuth(menuId, cond);
            cond = setSeachSql(cond);

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcgPurchaseOrderPay> util = new ExportExcelUtils<>(new TcgPurchaseOrderPay());
            String toFilePath = util.exportExcel(listData, listField, "采购付款");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 付款审核
     */
    @RequiresPermissions(PERMISSIONS+"examine")
    @RequestMapping("/examine")
    @ResponseBody
    public R examine(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(checkUtil.isNullByObject(params.get("choooseDatas"))){
                return R.error("请选择要操作的信息");
            }
            String choooseDatas = params.get("choooseDatas").toString();
            return tcgPurchaseOrderPayService.examine(choooseDatas);
        } catch (IllegalArgumentException e) {
            //logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 取消付款
     */
    @RequiresPermissions(PERMISSIONS+"cancel")
    @RequestMapping("/cancel")
    @ResponseBody
    public R cancel(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {

            if(checkUtil.isNullByObject(params.get("cancelType"))){
                return R.error("请选择取消方式");
            }
            if(checkUtil.isNullByObject(params.get("choooseDatas"))){
                return R.error("请选择要操作的信息");
            }
            String cancelType = params.get("cancelType").toString();//取消方式：0按计划、1按订单
            String choooseDatas = params.get("choooseDatas").toString();
            return tcgPurchaseOrderPayService.cancel(choooseDatas,cancelType);
        } catch (IllegalArgumentException e) {
            //logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 采购付款
     */
    @RequiresPermissions(PERMISSIONS+"onlinePay")
    @RequestMapping("/onlinePay")
    @ResponseBody
    public R onlinePay(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String goodsIds = params.get("goodsIds").toString();

            //获取可以进行付款的状态
            List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getPayStatus();
            //拼接
            String orders = TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList);

            //过滤，只有付款失败和订单待付款的，才可进行付款
            List<Map<String, Object>> groupsByList = new TcgPurchaseOrderPay()
                    .where("A.PurchasePlanGoodsId IN ("+goodsIds+")")
                    //.where("A.Id IN ("+payIds+")")
                    .addLeftJoin("TCG_PurchaseByOrder B ON A.PurchaseOrderBid = B.Bid")
                    .addField("B.AliOrderNumber AS aliOrderNumber")
                    .where("B.OrderStatus IN ("+orders+")")
                    .queryMap();
            if(groupsByList!=null && groupsByList.size()>0){
                /*
                //去重
                List<Map<String, Object>> resListByGroups = ToolUtil.groupsByList(groupsByList, e->e.get("id").toString());
                String aliOrderNos = "";
                for(Map<String, Object> item:resListByGroups){
                    if("".equals(aliOrderNos)){
                        aliOrderNos = item.get("aliOrderNumber").toString();
                    }else {
                        aliOrderNos += "," + item.get("aliOrderNumber").toString();
                    }
                }
                return api1688Service.get1688AlipayUrl(aliOrderNos);

                 */
                return R.ok();
            }else {
                return R.error("所选择的单据均不可进行采购付款");
            }

        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 采购付款 - 弹窗保存
     */
    @RequiresPermissions(PERMISSIONS+"onlinePay")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcgPurchaseOrderPayService.update(params,menuId);
        } catch (IllegalArgumentException e) {
            //logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


}